package com.old.nsi_class.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.nsi.util.MailUtil;
import com.nsi.util.PropertiesUtil;
import com.old.nsi_class.DB.Course_DB;
import com.old.nsi_class.DB.DateUtils;
import com.old.nsi_class.DB.JSONResult2;
import com.old.nsi_class.DB.JsonResult;
import com.old.nsi_class.model.ActivationCode;

@WebServlet("/Class_ActivationCode")
public class Class_ActivationCode_api extends HttpServlet {

    /**
     * 对象序列化
     */
    private static final long serialVersionUID = 5187861055372387075L;
    private Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doPost(req, res);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        String whereFrom = req.getParameter("whereFrom");
        String number = req.getParameter("Number");
        String text = req.getParameter("Text");
        /**
         * 激活码功能
         */
        if ("activationCode".equals(whereFrom)) {
            String courseId = req.getParameter("CourseId");
            String sql = "SELECT * FROM nsi_course WHERE Id='" + courseId + "';";
            int count = Course_DB.count(sql);
            //判断课程Id参数是否合法
            if (count > 0) {
                Pattern patten = Pattern.compile("[0-9]*");
                boolean flag = patten.matcher(number).matches();
                //判断生成课程激活码数量参数是否合法
                if (flag) {
                    int parseInt = Integer.parseInt(number);
                    //验证码字符串放到list集合当中
                    List<String> list = new ArrayList<String>();
                    for (int i = 0; i < parseInt; i++) {
                        //将课程Id转换成16进制
                        String hexString16 = Class_ActivationCode_api.hexString16(courseId);
                        //前3位和后3位随机数
                        String newStr = Class_ActivationCode_api.generateWord() + hexString16 + Class_ActivationCode_api.generateWord();
                        String valid = "0";
                        String sqlCode = "insert into nsi_activationcode "
                                + "(activationCode,loadTime,valid,text)values('" + newStr + "','" + DateUtils.onToday() + "','" + valid + "','" + text + "');";
                        Course_DB.commonMethod(sqlCode);
                        list.add(newStr);
                    }
                    JSONResult2 jr = new JSONResult2(list);
                    String data = gson.toJson(jr);
                    //插入Log信息
//					CommonLog_model cm = new CommonLog_model();
//					cm.setSign("新学说课堂"); 
//					LogUtils.insertLogInformation(cm);

                    JSONResult2.toResult(req, res, data);
                } else {
                    String message = "参数含有特殊符号或字母";
                    JSONResult2 jr = new JSONResult2(message);
                    String data = gson.toJson(jr);
                    JSONResult2.toResult(req, res, data);
                }
            } else {
                String message = "课程Id参数不合法";
                JSONResult2 jr = new JSONResult2(message);
                String data = gson.toJson(jr);
                JSONResult2.toResult(req, res, data);
            }

            /**
             * 课程购买码
             */
        } else if ("courseCode".equals(whereFrom)) {
            //获取验证码
            String code = req.getParameter("code");
            String userMail = req.getParameter("UserMail");
            String sql = "SELECT * FROM nsi_activationcode WHERE activationCode='" + code + "' AND valid='0';";
            int count = Course_DB.count(sql);
            if (count > 0) {
                String valid = "1";
                String sqlUpdate = "UPDATE nsi_activationcode SET valid='" + valid + "',userTime='" + DateUtils.onToday() + "' WHERE activationCode='" + code + "';";
                Course_DB.commonMethod(sqlUpdate);
                //截取code激活码中间5位
                String substring = code.substring(3, 7);
                //中间5位还原成10进制的课程Id
                String CourseId = Class_ActivationCode_api.restoreStr(substring);

                //购买业务执行
                String sql03 = "select * from nsi_course_user where ClassId= '" + CourseId + "' AND UserMail='" + userMail + "';";
                int count03 = Course_DB.count(sql03);
//				如果已存在，表示购买过
                if (count03 >= 1) {
                    System.out.println("已购买过该课程--内");
                    String message = "已购买过该课程!";
                    JSONResult2 jr = new JSONResult2(message);
                    String data = gson.toJson(jr);
                    JSONResult2.toResult(req, res, data);
//				未购买过该课程	
                } else {
                    System.out.println("已购买过该课程--外");
                    String sql02 = "insert nsi_course_user (ClassId,UserMail) values ('" + CourseId + "','" + userMail + "'); ";
                    int i = Course_DB.insert02(sql02);
                    if (i >= 1) {

                        //					支付成功：发送通知邮件
                        try {
                            String adminEmail = PropertiesUtil.getProperty("admin.email");
                            MailUtil.SendNotifyMail(adminEmail, "课程购买码成功: " + userMail + "-" + code + " ");
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            //						课程购买码成功 返回值
                            JSONResult2 jr = new JSONResult2();
                            String data = gson.toJson(jr);
                            JSONResult2.toResult(req, res, data);
                        }

                    } else {
                        String message = "购买失败!:后台业务执行失败！";
                        JSONResult2 jr = new JSONResult2(message);
                        String data = gson.toJson(jr);
                        JSONResult2.toResult(req, res, data);
                    }
                }

            } else {
                String message = "激活码无效!:激活码验证错误！";
                JSONResult2 jr = new JSONResult2(message);
                String data = gson.toJson(jr);
                JSONResult2.toResult(req, res, data);
            }

            /**
             * 显示所有激活码
             */
        } else if ("showCode".equals(whereFrom)) {
            //分页参数 ：第几页、每页几个。默认值：1、20；
            Integer pageNum = req.getParameter("pageNum") != null && !req.getParameter("pageNum").equals("") ? Integer.parseInt(req.getParameter("pageNum")) : 1;
            Integer OnePageNum = req.getParameter("OnePageNum") != null && !req.getParameter("OnePageNum").equals("") ? Integer.parseInt(req.getParameter("OnePageNum")) : 20;
            int pageNumX = (pageNum - 1) * OnePageNum;
            String sqlList = "SELECT * FROM nsi_activationcode Limit " + pageNumX + "," + OnePageNum + ";";
            List<ActivationCode> list = Course_DB.searchCode(sqlList);
            String sqlCount = "SELECT * FROM nsi_activationcode;";
            int rowCount = Course_DB.count(sqlCount);
            JSONResult2 jr = new JSONResult2(rowCount, list);
            String data = gson.toJson(jr);
            //返回结果集
            JSONResult2.toResult(req, res, data);

//		课程购买码 搜索
        } else if ("SearchCourseCode".equals(whereFrom)) {
            String sql = null;

            if (req.getParameter("code") != null && !req.getParameter("code").equals("")) {
                String code = req.getParameter("code");
                sql = "SELECT * FROM nsi_activationcode WHERE activationCode='" + code + "' limit 10;";
            } else {
                sql = "SELECT * FROM nsi_activationcode order by loadTime DESC limit 10;";
            }
            List<ActivationCode> list = new ArrayList<ActivationCode>();
            list = Course_DB.ActivationCodeSearch(sql);
            Gson gson = new Gson();
            String jsonList = gson.toJson(list);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().write("{\"data\":" + jsonList + "}");

            /**
             * 	封装错误信息
             */
        } else {
            //返回结果集
            JsonResult.toResultFault(req, res);
        }


    }

    /**
     * 随机生成3位字母和数字得组合
     *
     * @return 随机码
     */
    private static String generateWord() {
        String[] beforeShuffle = new String[]{"2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        List<String> list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(6, 9);
        return result;
    }

    /**
     * 转换成16进制字符串
     *
     * @param hexCode
     * @return
     */
    private static String hexString16(String hexCode) {
        Long num = Long.valueOf(hexCode);
        String HexCode = Long.toHexString(num);
        return HexCode;
    }

    /**
     * 还原成10进制字符串
     *
     * @param restoreStr
     * @return
     */
    private static String restoreStr(String restoreStr) {
        Long PurchaseCode_10 = Long.valueOf(restoreStr, 16);
        String newStr = String.valueOf(PurchaseCode_10);
        return newStr;
    }

    public static void main(String[] args) {

//		测试float
        String total_fee = "102";
        double total_fee00 = Double.parseDouble(total_fee);
        System.out.println("bb:" + total_fee00);
    }


}
